<template>
  <div>
    <el-dialog
      :title="
        !dataForm.id
          ? `新建[${getDict('topictype', dataForm.topictype)}]`
          : isDetail
          ? '详情'
          : `编辑题目[${getDict('topictype', dataForm.topictype)}]`
      "
      :close-on-click-modal="false"
      :visible.sync="visible"
      class="JADP-dialog JADP-dialog_center"
      lock-scroll
      width="70%"
      append-to-body
      @close="close"
    >
      <el-row :gutter="15" class="">
        <el-form
          ref="elForm"
          :model="dataForm"
          :rules="rules"
          size="small"
          label-position="right"
          :disabled="!!isDetail"
        >
          <el-col :span="24">
            <el-form-item label="难度" prop="difficultion">
              <el-radio-group v-model="dataForm.difficultion" size="small">
                <el-radio-button
                  v-for="(item, index) in getDict('difficultion')"
                  :key="index"
                  :label="item.id"
                  :disabled="item.disabled"
                >
                  {{ item.dataName }}
                </el-radio-button>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <div
            class="tips"
            v-if="dataForm.topictype === 'f0b4073bc9ad4426b87cbc70d4526cf6'"
          >
            <el-button type="primary" plain v-copy="copyText"
              >复制下划线</el-button
            >
            <el-button type="primary" plain @click="insertClick"
              >插入三个下划线</el-button
            >
            (提示：连续三个下划线"_"表示一个填空项,可快捷添加)
          </div>
          <div class="part_card">
            <div class="part_card_header">题干</div>
            <div class="part_card_body">
              <JADP-Quill
                v-model="dataForm.stem"
                placeholder="请输入内容..."
                ref="myQuillEditor"
              >
              </JADP-Quill>
            </div>
          </div>
          <!-- 单选题  -->
          <div
            class="part_card"
            v-if="dataForm.topictype === '7280c24ba6bf410997c739637706e7e6'"
          >
            <div class="part_card_header">答案</div>
            <div class="part_card_body">
              <el-row style="margin-bottom: 10px">
                <el-col :span="3" style="text-align: center">正确答案</el-col>
                <el-col :span="15" style="text-align: center">选项内容</el-col>
                <el-col :span="6" style="text-align: center">操作</el-col>
              </el-row>
              <el-row
                v-for="(item, index) in letterList.slice(0, option)"
                :key="index"
              >
                <el-col :span="3" style="text-align: center" class="myradio">
                  <el-radio-group v-model="dataForm.result">
                    <el-radio :label="item.id"></el-radio>
                  </el-radio-group>
                </el-col>
                <el-col :span="15" style="text-align: center">
                  <div class="part_card">
                    <div class="part_card_header">{{ item.label }}</div>
                    <div class="part_card_body">
                      <el-input
                        v-model="item.value"
                        placeholder="请输入内容"
                      ></el-input>
                    </div>
                  </div>
                </el-col>
                <el-col :span="6" style="text-align: center; padding-top: 10px">
                  <el-col :span="6">
                    <el-button
                      type="primary"
                      icon="el-icon-plus"
                      circle
                      @click="addOption(item)"
                    ></el-button
                  ></el-col>
                  <el-col :span="6">
                    <el-button
                      type="primary"
                      icon="el-icon-minus"
                      circle
                      @click="subtractOption(item)"
                    ></el-button
                  ></el-col>
                  <el-col :span="6">
                    <el-button
                      type="primary"
                      icon="el-icon-arrow-up"
                      circle
                      @click="moveUp(item)"
                    ></el-button
                  ></el-col>
                  <el-col :span="6">
                    <el-button
                      type="primary"
                      icon="el-icon-arrow-down"
                      circle
                      @click="moveDown(item)"
                    ></el-button
                  ></el-col>
                </el-col>
              </el-row>
            </div>
          </div>
          <!-- 多选题  -->
          <div
            class="part_card"
            v-if="dataForm.topictype === '1d3f7e7e22c94e49ba95f52e3ec9e3af'"
          >
            <div class="part_card_header">答案</div>
            <div class="part_card_body">
              <el-row style="margin-bottom: 10px">
                <el-col :span="3" style="text-align: center">正确答案</el-col>
                <el-col :span="15" style="text-align: center">选项内容</el-col>
                <el-col :span="6" style="text-align: center">操作</el-col>
              </el-row>
              <el-row
                v-for="(item, index) in letterList.slice(0, option)"
                :key="index"
              >
                <el-col :span="3" style="text-align: center" class="myradio">
                  <el-checkbox-group v-model="dataForm.result">
                    <el-checkbox :label="item.id"></el-checkbox>
                  </el-checkbox-group>
                </el-col>
                <el-col :span="15" style="text-align: center">
                  <div class="part_card">
                    <div class="part_card_header">{{ item.label }}</div>
                    <div class="part_card_body">
                      <el-input
                        v-model="item.value"
                        placeholder="请输入内容"
                      ></el-input>
                    </div>
                  </div>
                </el-col>
                <el-col :span="6" style="text-align: center; padding-top: 10px">
                  <el-col :span="6">
                    <el-button
                      type="primary"
                      icon="el-icon-plus"
                      circle
                      @click="addOption(item)"
                    ></el-button
                  ></el-col>
                  <el-col :span="6">
                    <el-button
                      type="primary"
                      icon="el-icon-minus"
                      circle
                      @click="subtractOption(item)"
                    ></el-button
                  ></el-col>
                  <el-col :span="6">
                    <el-button
                      type="primary"
                      icon="el-icon-arrow-up"
                      circle
                      @click="moveUp(item)"
                    ></el-button
                  ></el-col>
                  <el-col :span="6">
                    <el-button
                      type="primary"
                      icon="el-icon-arrow-down"
                      circle
                      @click="moveDown(item)"
                    ></el-button
                  ></el-col>
                </el-col>
              </el-row>
            </div>
          </div>
          <!-- 填空题  -->
          <div
            class="part_card"
            v-if="dataForm.topictype === 'f0b4073bc9ad4426b87cbc70d4526cf6'"
          >
            <div class="part_card_header">答案</div>
            <div class="part_card_body">
              <el-row v-for="(item, index) in tianKong" :key="index">
                <el-col :span="24" style="text-align: center">
                  <div class="part_card">
                    <div class="part_card_header" style="width: 100px">
                      第{{ index + 1 }}空答案
                    </div>
                    <div class="part_card_body">
                      <el-input
                        v-model="item.value"
                        placeholder="请输入内容"
                      ></el-input>
                    </div>
                  </div>
                </el-col>
              </el-row>
            </div>
          </div>
          <!-- 判断题  -->
          <div
            class="part_card"
            v-if="dataForm.topictype === 'ee505074164e4d0bb54e4a5136b123fb'"
          >
            <div class="part_card_header">答案</div>
            <div class="part_card_body">
              <el-radio-group v-model="dataForm.result" style="margin-top: 8px">
                <el-radio label="正确"></el-radio>
                <el-radio label="错误"></el-radio>
              </el-radio-group>
            </div>
          </div>
          <!-- 简答题  -->
          <div
            class="part_card"
            v-if="dataForm.topictype === '07ba1e3b779b4e1db3c1318d0f80a688'"
          >
            <div class="part_card_header">答案</div>
            <div class="part_card_body">
              <JADP-Quill v-model="dataForm.result" placeholder="请输入内容...">
              </JADP-Quill>
            </div>
          </div>

          <div class="part_card">
            <div class="part_card_header">答案解析</div>
            <div class="part_card_body">
              <JADP-Quill
                v-model="dataForm.answeranalysis"
                placeholder="请输入内容..."
              >
              </JADP-Quill>
            </div>
          </div>

          <div class="part_card">
            <div class="part_card_header">知识点</div>
            <div class="part_card_body">
              <el-tag
                v-for="tag in tags"
                :key="tag.id"
                closable
                @close="handleClose(tag)"
                style="margin-right: 10px;margin-bottom: 5px"
              >
                {{ tag.name }}
              </el-tag>
              <el-button
                type="success"
                icon="el-icon-circle-plus-outline"
                @click="addKnowledgePoints"
                >添加知识点</el-button
              >
            </div>
          </div>
        </el-form>
      </el-row>

      <span slot="footer" class="dialog-footer">
        <el-button @click="visible = false">取 消</el-button>
        <el-button type="primary" @click="dataFormSubmit()" v-if="!isDetail"
          >确 定</el-button
        >
      </span>
    </el-dialog>
    <el-dialog
      title="设置题目知识点"
      append-to-body
      :close-on-click-modal="false"
      :visible.sync="knowledgePointsVisible"
      lock-scroll
      class="JADP-dialog JADP-dialog_center"
      width="60%"
      v-if="knowledgePointsVisible"
    >
      <el-row class="JADP-common-search-box" :gutter="16">
        <el-form @submit.native.prevent>
          <!-- <el-col :span="6">
            <el-form-item label="知识点分类" prop="assortment">
              <JADP-TreeSelect
                v-model="query.assortment"
                :options="treeData"
                placeholder="选择分类"
                style="width: 100%"
              />
            </el-form-item>
          </el-col> -->
          <el-col :span="6">
            <el-form-item label="知识点名称">
              <el-input v-model="query.name" placeholder="请输入" clearable>
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item>
              <el-button type="primary" icon="el-icon-search" @click="search()"
                >查询</el-button
              >
              <el-button icon="el-icon-refresh-right" @click="reset()"
                >重置</el-button
              >
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <el-table
        v-loading="listLoading"
        :data="list"
        @sort-change="sortChange"
        @selection-change="handleSelectionChange"
        row-key="id"
      >
        <el-table-column type="selection" width="55" reserve-selection>
        </el-table-column>
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="知识点名称" align="left" />
        <!-- <el-table-column label="知识点分类" prop="assortment" algin="left"> -->
        <!-- </el-table-column> -->
        <el-table-column
          prop="creatortime"
          label="创建时间"
          align="left"
          sortable="custom"
        />
      </el-table>
      <pagination
        :total="total"
        :page.sync="listQuery.currentPage"
        :limit.sync="listQuery.pageSize"
        @pagination="initData"
      />
      <span slot="footer" class="dialog-footer">
        <el-button @click="knowledgePointsVisible = false">取 消</el-button>
        <el-button type="primary" @click="KnowledgePointDetermination"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import request from "@/utils/request";
import ExportBox from "./ExportBox";
export default {
  name: "abc",
  components: { ExportBox },
  props: ["tkid"],
  data() {
    return {
      loading: false,
      visible: false,
      knowledgePointsVisible: false,
      isDetail: false,
      option: 4, //默认展示4个选项
      activeName: "",
      dataForm: {
        topictype: "",
        difficultion: "",
        stem: "",
        result: "",
        optionsum: undefined,
        answeranalysis: undefined,
        creatoruserid: "",
        creatortime: "",
        lastmodifyuserid: "",
        lastmodifytime: "",
        zsdid: ""
      },

      rules: {},
      index: 0,
      copyText: "___",
      letterList: [
        { label: "A", index: 0, value: "选项1", id: "A" },
        { label: "B", index: 1, value: "选项2", id: "B" },
        { label: "C", index: 2, value: "选项3", id: "C" },
        { label: "D", index: 3, value: "选项4", id: "D" },
        { label: "E", index: 4, value: "选项5", id: "E" },
        { label: "F", index: 5, value: "选项6", id: "F" },
        { label: "G", index: 6, value: "选项7", id: "G" },
        { label: "H", index: 7, value: "选项8", id: "H" },
        { label: "I", index: 8, value: "选项9", id: "I" },
        { label: "J", index: 9, value: "选项10", id: "J" },
        { label: "K", index: 10, value: "选项11", id: "K" },
        { label: "L", index: 11, value: "选项12", id: "L" },
        { label: "M", index: 12, value: "选项13", id: "M" },
        { label: "N", index: 13, value: "选项14", id: "N" },
        { label: "O", index: 14, value: "选项15", id: "O" },
        { label: "P", index: 15, value: "选项16", id: "P" },
        { label: "Q", index: 16, value: "选项17", id: "Q" },
        { label: "R", index: 17, value: "选项18", id: "R" },
        { label: "S", index: 18, value: "选项19", id: "S" },
        { label: "T", index: 19, value: "选项20", id: "T" },
        { label: "U", index: 20, value: "选项21", id: "U" },
        { label: "V", index: 21, value: "选项22", id: "V" },
        { label: "W", index: 22, value: "选项23", id: "W" },
        { label: "X", index: 23, value: "选项24", id: "X" },
        { label: "Y", index: 24, value: "选项25", id: "Y" },
        { label: "Z", index: 25, value: "选项26", id: "Z" }
      ],
      tianKong: [],
      arrNum: 0,
      list: [],
      listLoading: true,
      multipleSelection: [],
      total: 0,
      listQuery: {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "creatortime"
      },
      query: {
        assortment: undefined,
        name: undefined
      },
      treeData: [],
      tags: [],
      zsdList: []
    };
  },
  computed: {},
  watch: {
    "dataForm.stem": {
      handler(val) {
        if (this.dataForm.topictype === "f0b4073bc9ad4426b87cbc70d4526cf6") {
          var patt1 = /___/g;
          let arr = val.match(patt1);
          if (arr && arr.length) {
            if (arr.length > this.tianKong.length) {
              for (let i = 0; i < arr.length - this.tianKong.length; i++) {
                this.tianKong.push({
                  value: ""
                });
              }
            }
          }
        }
      }
    }
  },
  created() {
    this.initData();
    this.getTreeData();
    this.getzsdList();
  },
  mounted() {},
  methods: {
    init(subjectName, id, isDetail) {
      this.dataForm.topictype = subjectName;
      // 判断题的类型
      if (this.dataForm.topictype === "1d3f7e7e22c94e49ba95f52e3ec9e3af") {
        this.dataForm.result = ["A", "B"];
      } else if (
        this.dataForm.topictype === "7280c24ba6bf410997c739637706e7e6"
      ) {
        this.dataForm.result = "A";
      }
      this.dataForm.id = id || 0;
      this.dataForm.tkid = this.tkid;
      this.visible = true;
      this.isDetail = isDetail || false;
      this.$nextTick(() => {
        this.$refs["elForm"].resetFields();
        if (this.dataForm.id) {
          this.loading = true;
          request({
            url: "/api/subject/Xy_ks_subject/" + this.dataForm.id,
            method: "get"
          }).then(res => {
            this.dataForm = res.data;
            if (this.dataForm.zsdid) {
              let tagsId = this.dataForm.zsdid.split(",");
              let newArr = [];
              tagsId.forEach(item => {
                newArr.push(this.zsdList.filter(value => item === value.id));
              });
              this.tags = newArr.flat();
              console.log(this.tags, 333);
            } else {
              this.tags = [];
            }
            this.optionsumList = JSON.parse(this.dataForm.optionsum);
            if (
              this.dataForm.topictype !== "07ba1e3b779b4e1db3c1318d0f80a688" &&
              this.dataForm.topictype !== "ee505074164e4d0bb54e4a5136b123fb"
            ) {
              this.dataForm.result = JSON.parse(this.dataForm.result);
            }

            if (
              this.dataForm.topictype === "1d3f7e7e22c94e49ba95f52e3ec9e3af" ||
              this.dataForm.topictype === "7280c24ba6bf410997c739637706e7e6"
            ) {
              this.letterList.forEach(item => {
                this.optionsumList.forEach(value => {
                  if (value.id == item.id) {
                    item.value = value.value;
                  }
                });
              });
            } else if (
              this.dataForm.topictype === "f0b4073bc9ad4426b87cbc70d4526cf6"
            ) {
              //判断填空题
              this.tianKong = JSON.parse(this.dataForm.optionsum);
            }
            this.loading = false;
          });
        }
      });
    },
    // 表单提交
    dataFormSubmit() {
      this.$refs["elForm"].validate(valid => {
        if (valid) {
          if (
            this.dataForm.topictype === "7280c24ba6bf410997c739637706e7e6" ||
            this.dataForm.topictype === "1d3f7e7e22c94e49ba95f52e3ec9e3af"
          ) {
            let optionsumList = [];
            for (let i = 0; i < this.option; i++) {
              optionsumList.push(this.letterList[i]);
            }
            this.dataForm.optionsum = JSON.stringify(optionsumList);
            this.dataForm.result = JSON.stringify(this.dataForm.result);
          } else if (
            this.dataForm.topictype === "f0b4073bc9ad4426b87cbc70d4526cf6"
          ) {
            // 填空题
            this.dataForm.optionsum = JSON.stringify(this.tianKong);
            this.dataForm.result = this.dataForm.optionsum;
          }
          this.dataForm.zsdid = this.tags.map(item => item.id).join();

          // else if (
          //   // 判断简答题
          //   this.dataForm.topictype !== "07ba1e3b779b4e1db3c1318d0f80a688"
          // ) {
          //   this.dataForm.optionsum = JSON.stringify(this.tianKong);
          // }
          if (!this.dataForm.id) {
            request({
              url: `/api/subject/Xy_ks_subject`,
              method: "post",
              data: this.dataForm
            }).then(res => {
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1000,
                onClose: () => {
                  (this.visible = false), this.$emit("refresh", true);
                }
              });
            });
          } else {
            request({
              url: "/api/subject/Xy_ks_subject/" + this.dataForm.id,
              method: "PUT",
              data: this.dataForm
            }).then(res => {
              this.$message({
                message: res.msg,
                type: "success",
                duration: 1000,
                onClose: () => {
                  this.visible = false;
                  this.$emit("refresh", true);
                }
              });
            });
          }
        }
      });
    },
    // 插入下划线
    insertClick() {
      // 文本内容
      const text = "___";
      // 获取编辑器对象
      var quill = this.$refs.myQuillEditor.editor;

      // 获取编辑器光标位置
      let index = quill.selection.savedRange.index;
      if (index !== 0 && this.index == index) return;

      // 插入文本至光标位置，
      quill.insertText(index, text);

      // 重新计算index
      index += text.length;
      this.index = index;

      // 移动光标至文本后面
      quill.setSelection(index);
    },
    //新增选项
    addOption(item) {
      if (this.option <= 25) {
        this.option++;
        for (let i = this.option; i > item.index; i--) {
          this.letterList[i].value = this.letterList[i - 1].value;
          //   this.letterList[i].id = this.letterList[i - 1].id;
        }
        this.letterList[item.index + 1].value = `选项${item.index + 2}`;
        this.letterList[item.index + 1].id = this.letterList[
          item.index + 1
        ].label;
      } else {
        this.$message({
          message: "最多只能添加26个选项",
          type: "warning",
          duration: 1000
        });
      }
    },

    // 减少选项
    subtractOption(item) {
      if (this.option > 1) {
        this.option--;
        for (let i = item.index; i < this.letterList.length - 1; i++) {
          this.letterList[i].value = this.letterList[i + 1].value;
          this.letterList[i].id = this.letterList[i + 1].id;
        }
      } else {
        this.$message({
          message: "最少保留一个选项",
          type: "warning",
          duration: 1000
        });
      }
    },
    // 下移选项
    moveDown(item) {
      if (item.index < this.option - 1) {
        let temp = this.letterList[item.index].value;
        let tempId = this.letterList[item.index].id;
        this.letterList[item.index].value = this.letterList[
          item.index + 1
        ].value;
        this.letterList[item.index].id = this.letterList[item.index + 1].id;
        this.letterList[item.index + 1].value = temp;
        this.letterList[item.index + 1].id = tempId;
      } else {
        this.$message({
          message: "已经是最后一个选项",
          type: "warning",
          duration: 1000
        });
      }
    },
    // 上移选项
    moveUp(item) {
      if (item.index > 0) {
        let temp = this.letterList[item.index].value;
        let tempId = this.letterList[item.index].id;
        this.letterList[item.index].value = this.letterList[
          item.index - 1
        ].value;
        this.letterList[item.index].id = this.letterList[item.index - 1].id;
        this.letterList[item.index - 1].value = temp;
        this.letterList[item.index - 1].id = tempId;
      } else {
        this.$message({
          message: "已经是第一个选项了",
          type: "warning",
          duration: 1000
        });
      }
    },
    // 添加知识点
    addKnowledgePoints() {
      this.knowledgePointsVisible = true;
    },
    //移除知识点
    handleClose(tag) {
      this.multipleSelection.splice(this.multipleSelection.indexOf(tag), 1);
    },
    // 知识点分类
    getTreeData() {
      this.request({
        url: "/api/xy_ks_knowlege_type/Xy_ks_knowlege_type/getTreeList",
        method: "get"
      }).then(res => {
        let topItem = {
          fullName: "默认",
          hasChildren: true,
          id: "-1",
          icon: "icon-ym icon-ym-tree-organization3",
          children: res.data
        };
        this.treeData = [topItem];
      });
    },
    //知识点list
    initData() {
      this.listLoading = true;
      let _query = {
        ...this.listQuery,
        ...this.query,
        organizeId:this.$store.getters.organizeId
      };
      let query = {};
      for (let key in _query) {
        if (Array.isArray(_query[key])) {
          query[key] = _query[key].join();
        } else {
          query[key] = _query[key];
        }
      }
      request({
        url: `/api/knowledgepoint/Xy_ks_knowledgepoint`,
        method: "get",
        data: query
      }).then(res => {
        this.list = res.data.list;
        this.total = res.data.pagination.total;
        this.listLoading = false;
      });
    },
    handleSelectionChange(val) {
      // const res = val.map(item => item.id);
      this.multipleSelection = val;
    },
    KnowledgePointDetermination() {
      this.tags = this.multipleSelection;
      this.knowledgePointsVisible = false;
    },
    sortChange({ column, prop, order }) {
      this.listQuery.sort = order == "ascending" ? "asc" : "desc";
      this.listQuery.sidx = !order ? "" : prop;
      this.initData();
    },
    search() {
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "creatortime"
      };
      this.initData();
    },
    reset() {
      for (let key in this.query) {
        this.query[key] = undefined;
      }
      this.listQuery = {
        currentPage: 1,
        pageSize: 20,
        sort: "desc",
        sidx: "creatortime"
      };
      this.initData();
    },
    //关闭弹窗
    close() {
      this.dataForm = {
        topictype: "",
        difficultion: "",
        stem: undefined,
        result: undefined,
        optionsum: undefined,
        answeranalysis: undefined,
        creatoruserid: "",
        creatortime: "",
        lastmodifyuserid: "",
        lastmodifytime: ""
      };
    },
    // 获取全部知识点list
    getzsdList() {
      request({
        url: `/api/knowledgepoint/Xy_ks_knowledgepoint/getAllList`,
        method: "get"
      }).then(res => {
        this.zsdList = res.data;
      });
    }
  }
};
</script>

<style scoped lang="scss">
.tips {
  color: #f66042;
  font-size: 16px;
  font-weight: 600;
  padding-bottom: 10px;
  padding-left: 10px;
}
.part_card {
  min-height: 50px;
  display: flex;
  margin-bottom: 20px;
  border: 1px solid #d2d2d2;
  border-radius: 4px;
  .part_card_header {
    -webkit-box-flex: 0;
    flex: none;
    width: 70px;
    display: flex;
    -webkit-box-pack: center;
    justify-content: center;
    -webkit-box-align: center;
    align-items: center;
    background-color: #f5f7fa;
    font-weight: 700;
    border-right: 1px solid #ccc;
  }
  .part_card_body {
    -webkit-box-flex: 1;
    flex: 1;
    padding: 10px;
    .myradio {
      padding-top: 20px;
      >>> .el-radio__label {
        display: none;
      }
      >>> .el-radio__inner {
        transform: scale(1.3);
      }
      >>> .el-checkbox__label {
        display: none;
      }
      >>> .el-checkbox__inner {
        transform: scale(1.3);
      }
    }
  }
}
</style>
